<?php

ptaste();
require_once(dirname(__FILE__)."/classes.php");


class DbResult
{
	var $parent=false;
	var $rowcnt=-1;
	var $colcnt=-1;
	var $res=false;
	var $currow=0;
	
	function __construct($parent,$res)
	{
		$this->parent=$parent;
		$this->res=$res;
	}
	
	function __destruct()
	{
	}
	
	function rows()
	{
		if ($this->rowcnt==-1)
			$this->rowcnt=mysql_num_rows($this->res);
		return $this->rowcnt;
	}
	
	function cols()
	{
		if ($this->colcnt==-1)
			$this->colcnt=mysql_num_fields($this->res);
		return $this->colcnt;
	}
	
	function fieldname($index)
	{
	  if ($index<0 || $index>=$this->cols())
	    return false;
	  return mysql_field_name($this->res,$index);
	}
	
	function getrow($index)
	{
		if ($index<0 || $index>=$this->rows())
			return false;
		mysql_data_seek($this->res,$index);
		return mysql_fetch_row($this->res);
	}
	
	function agetrow($index)
	{
		if ($index<0 || $index>=$this->rows())
			return false;
		mysql_data_seek($this->res,$index);
		return mysql_fetch_assoc($this->res);
	}
	
	function rewind()
	{
	  $this->currow=0;
	}
	
	function first()
	{
		$this->currow=0;
		return $this->next();
	}

	function next()
	{
		$rs=$this->getrow($this->currow);
		$this->currow++;
		return $rs;
	}
	
	function afirst()
	{
		$this->currow=0;
		return anext();
	}
	
	function anext()
	{
		$rs=$this->agetrow($this->currow);
		$this->currow++;
		return $rs;
	}
}

class DbConnection extends SiteObject
{
	var $link=false;
	
	function __construct($site,$logger=null,$host="",$user="",$password="",$dbname="")
	{
		parent::__construct($site,$logger);
		if ($host=="" && $user=="")
		{
			$cnf=$site->conf();
			$host=$cnf->get('db_host');
			$user=$cnf->get('db_user');
			$password=$cnf->get('db_password');
			$dbname=$cnf->get('db_name');
		}else if ($host=="") {
			$cnf=$site->conf();
			$host=$cnf->get('db_host');
		}
		$this->link=mysql_connect($host,$user,$password);
		if (!$this->link)
			die("DBError: can't connect to db ".mysql_error());
		mysql_select_db($dbname,$this->link) || die("DBerror: can't connect to db ".mysql_error($this->link));
		$this->queryf("SET character set utf8;");
	}
	
	function __destruct()
	{
		if ($this->link)
			mysql_close($this->link);
	}
	
	function unhack($data)
	{
	  return mysql_real_escape_string($data);
	}
	
	function queryf()
	{
		$args=func_get_args();
		$fmt=array_shift($args);
		$qry=vsprintf($fmt,$args);
	//	$this->logger()->debug("query=%s",$qry);
		$res=mysql_query($qry,$this->link);
		if ($res)
		{
		  $dbres=new DbResult($this,$res);
		  return $dbres;
		}
		$this->logger()->error("QRY ERROR: %s in query %s",mysql_error($this->link),$qry);
		return false;
	}
	
	function lastid()
	{
		$res=$this->queryf("SELECT LAST_INSERT_ID();");
		if (!$res) return false;
		if ($res->rows()!=1) return false;
		$rw=$res->next();
		if (!$rw) return false;
		return $rw[0];
	}
}

?>